package com.tsfyun.scm.config.mock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.*;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Description:
 * @CreateDate: Created in 2021/12/10 11:01
 */
@Slf4j
public class MockEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private static final String PROPERTY_SOURCE_NAME = "defaultProperties";

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        String isMockEnable = environment.getProperty("mock.enabled");
        if(StringUtils.isEmpty(isMockEnable) || !Boolean.valueOf(isMockEnable)) {
            return;
        }
        MutablePropertySources mutablePropertySources = environment.getPropertySources();
        String targetUrl = environment.getProperty("mock.url");
        Assert.hasText(targetUrl,"please config mock.url if mock is enable");
        log.info("已开启feign mock模式");
        Map<String, Object> map = new HashMap<>();
        map.put("ribbon.eureka.enabled",false);
        map.put("ribbon.listOfServers",targetUrl);
        //强制设置spring.sleuth.feign.enabled为false,因为不能共存，强制设置不生效
        //map.put("spring.sleuth.feign.enabled",false);

        MapPropertySource target = null;
        if(mutablePropertySources.contains(PROPERTY_SOURCE_NAME)) {
            PropertySource source = mutablePropertySources.get(PROPERTY_SOURCE_NAME);
            if(source instanceof MapPropertySource) {
                target = (MapPropertySource) source;

                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    String k = entry.getKey();
                    Object v = entry.getValue();
                    if (!target.containsProperty(k)) {
                        target.getSource().put(k,v);
                    }
                }
            }
        }

        if(null == target) {
            target = new MapPropertySource(PROPERTY_SOURCE_NAME,map);
        }

        if(!mutablePropertySources.contains(PROPERTY_SOURCE_NAME)) {
            mutablePropertySources.addLast(target);
        }

    }

}
